<?php
namespace app\common\model;
class Product extends BaseModel
{
    protected $table = 'product';

    public function getImageAttr($value)
    {
        return addImagePrefix($value);
    }
    public function setImageAttr($value)
    {
        return removeImagePrefix($value);
    }
    public function getSliderImageAttr($value)
    {
        $value = json_decode($value, true);
        if(!empty($value)) {
            foreach ($value as &$v) {
                $v = addImagePrefix($v);
            }
        }
        return $value;
    }
    public function setSliderImageAttr($value)
    {
        $value = json_decode($value, true);
        if(!empty($value)) {
            foreach ($value as &$v) {
                $v = removeImagePrefix($v);
            }
        }
        return json_encode($value);
    }

    public function spec()
    {
        return $this->hasMany('\app\common\model\ProductSpec', 'goods_id')->where('is_del', 0);
    }

    public function specOne()
    {
        return $this->hasOne('\app\common\model\ProductSpec', 'goods_id')->where('is_default', 1)->bind('price,suk,stock');
    }

    public function getStatusAttr($value)
    {
        $status = config('status.product');
        return isset($status[$value]) ? $status[$value] : $value;
    }
    public static function changeStatus($id, $mer_id = null)
    {
        if($mer_id) $goods = self::where('id',$id)->where('mer_id', $mer_id)->find();
        else $goods = self::find($id);

        if(!$goods) return ['code' => 0,'msg' => '未知商品'];

        if($goods->spec()->where('is_del',0)->count() == 0){
            return ['code' => 0,'msg' => '因价格未设置不能上架'];
        }
        $goods->status = ($goods->getData('status') == 1) ? 0 : 1;
        if ($goods->save())
            return ['code' => 1, 'msg' => $goods->status];
        else
            return ['code' => 0, 'msg' => '操作失败'];
    }
}